package com.bdcom.autotest.util;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import javax.imageio.ImageIO;

import com.bdcom.autotest.interaction.db.CheckMysql;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bdcom.autotest.interaction.step.FlowBean;
import com.bdcom.autotest.interaction.step.StepBean;
import com.bdcom.autotest.ui.gif.ImgFactory;

import static com.bdcom.autotest.interaction.http.NetcardUtil.loadAllNetcards;


public class Prop {
	
	private static Logger log = LoggerFactory.getLogger(Prop.class);
	
	
	public static final String JPG  = ".jpg";
	
	public static boolean isProd = false;
	
	public static String fffSep = "/";
	public static String baseDir = "";
	
	public static String serverIP = "127.0.0.1";
	public static String serverPort = "8088";
	public static String username = "xiaohong";

	public static String console_server_ip = "";
	public static int[] console_server_port =new int[8];
	public static String tftp_ip = "";
	public static int MYSQL_PORT = 3306;
	public static String MYSQL_HOST = "127.0.0.1";
	public static String MYSQL_DB = "autotestdb";
	public static String binDir = System.getProperty("user.dir") + fffSep+"bin";
	public static void init( String[] args ) {
		baseDir = System.getProperty("user.dir");
		baseDir =baseDir.replace("\\",fffSep);
		
		if( args!= null && args.length>0 ) {
			isProd = Boolean.parseBoolean( args[0]);
		}
		if( isProd ) {
//			redirectSystemOut();
		}

//		startMysql();
		loadServerConfig();
		loadTestFiles();
		//loadTipImgs();
		loadDevTypeMapping();
		loadDevConfig();
		loadTestType();
//		loadAllNetcards();
	}


	public static Map<String, Image> keyToImage = new HashMap<>();
	public static LinkedHashMap<String , FlowBean> flows = new LinkedHashMap<String , FlowBean>();
	public static List<String> menus = new ArrayList();

	private static void loadTipImgs() {
		Collection<FlowBean> values = flows.values();
		for(  FlowBean fb : values   ) {
			String picDir = fb.getPicDir();
			File dirFile = new File(picDir);
			File[] listFiles = dirFile.listFiles();
			for( File  img :listFiles ) {
				String name = img.getName();
				if( name.endsWith(JPG)  ) {
					String imgKey = picDir+"/" + name.substring(0 , name.indexOf(JPG));
					try {
						double maxw = 470;
						double maxh = 400;
						BufferedImage read = ImageIO.read( img );
						int width = read.getWidth();
						int height = read.getHeight();
						int imageww = width;
						int imagehh = height;
						if(  width >= maxw || height>maxh ) {
							double a = maxw/width;
							double b = maxh/ height;
							
							double usescale =a; 
							if(  a>b  ) {
								usescale = b; 
							}
							imageww = (int) (usescale*width);
							imagehh = (int) (usescale * height);
						}
						Image loadIconScale = ImgFactory.loadIconScale( img  , imageww , imagehh ) ;
						keyToImage.put(imgKey, loadIconScale);
					} catch (Exception e) {
						log.error( "" ,e );
					}
				}
			}
			
			
		}
	}

	
	
	
	private static void loadTestFiles() {
//		FileInputStream fis;
//		Integer devType = 1;
//		try {
//			Properties type = new Properties();
//			fis = new FileInputStream(getFile("devType.properties"));
//			type.load(fis);
//			devType = Integer.valueOf((String) type.get("devType"));
//			fis.close();
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		String fname = "";
//		if(devType==1){
//			fname = "tf/";
//		}else{
//			fname = "tf95/";
//		}
		String fname = "tf/";
		File file = getFile(fname);
		File[] listFiles = file.listFiles();
		for(   File ff :  listFiles ) {
			FlowBean fb = loadTestFile(ff);
			if(fb.isMenu()){
				menus.add(fb.getName());
			}
			flows.put( fb.getName()  , fb);
		}
	}


	
    private static FlowBean loadTestFile( File xmlFile  ) {
    	FlowBean fb = new FlowBean();
    	try {
			SAXReader reader = new SAXReader();
			Document doc = reader.read( xmlFile );
			Element root = doc.getRootElement();
			
			String fname = root.attribute("name").getValue();
			fb.setName(fname);
			String snPanelClass = root.attribute("snPanelClass").getValue();
			fb.setSnPanelClass(snPanelClass);
			String picDir = root.attribute("picDir").getValue();
			fb.setPicDir(picDir);
			String isMenu = root.attribute("isMenu").getValue();
			fb.setMenu("true".equals(isMenu)?true:false);
			Iterator iter = root.elementIterator();
			while (iter.hasNext()) {
				Element child = (Element) iter.next();
				String name = child.attribute("name").getValue();
				String type = StepBean.type_step;
				Attribute attribute = child.attribute("type");
				if( attribute != null ) {
					type = attribute.getValue();
				}
				String desc = child.attribute("desc").getValue();
				StepBean stepBean = new StepBean(name , type ,desc);
				
				
				Attribute attrTip = child.attribute("tip");
				Attribute attrHandleclass = child.attribute("handleclass");
				Attribute attrhh = child.attribute("hh");
				Attribute attrbtn = child.attribute("btn");
				Attribute attrRepeat = child.attribute("repeat");
				if( attrTip != null   ) {
					stepBean.setTip(  attrTip.getValue()  );
				}
				if( attrHandleclass != null   ) {
					stepBean.setHandleclass(   attrHandleclass.getValue()  );
				}
				if( attrhh != null   ) {
					stepBean.setHh( Integer.parseInt( attrhh.getValue()  )    );
				}
				if( attrbtn != null   ) {
					stepBean.setBtn(   attrbtn.getValue()     );
				}
				if( attrRepeat != null   ) {
					stepBean.setRepeat(  Boolean.parseBoolean( attrRepeat.getValue() )     );
				}
				fb.addStep(stepBean);
			}
		} catch (DocumentException e) {
			e.printStackTrace(); 
		}

    	return fb;
	}



	private static File getFile(String fname) {
		String path = "conf/"+fname;
		File file = new File(path);
		return file;
	}



	public static void redirectSystemOut() {
        try {
        	String fileDir = getBaseDir()+"/logs/";
        	File file = new File(fileDir);
        	if(  !file.exists() ) {
        		file.mkdirs();
        	}
        	String filePath = fileDir + "sysout.log";
        	file = new File(fileDir);
        	if(  !file.exists() ) {
        		file.createNewFile();
        	}
            System.setOut(new PrintStream(new FileOutputStream(filePath) ));
            System.setErr(new PrintStream(new FileOutputStream(filePath) ));

        } catch (Exception ex) {
            ex.printStackTrace();
            return;
        }


    }

	public static String getBaseDir() {
		
		if( StringUtils.isEmpty(baseDir)  ) {
			baseDir = System.getProperty("user.dir");
			baseDir =baseDir.replace("\\",fffSep);
		}
		return baseDir;
	} 
		
	
	
	public static void main(String[] args) {
//		System.out.println(    getBaseDir()  );
//		System.out.println( System.getProperty("java.library.path") );
		
		
		String picDir =" a/b/c";
		String name = "aaa.jpg";
		String imgKey = picDir+"/" + name.substring(0 , name.indexOf(JPG));
		
		System.out.println(imgKey);
	}
	
	public static JSONArray deviceTypeArr = new JSONArray();
	public static void loadDevTypeMapping(){
		File file = getFile("deviceTypeMapping.xml");
		SAXReader reader = new SAXReader();
		Document doc = null;
		try {
			doc = reader.read(file);
		} catch (Exception e) {
			return;
		}
		Element root = doc.getRootElement();
		List<Element> modules = root.elements();
		for( Element module : modules  ){
			String frontCode1 = module.attributeValue("frontCode1");
			String frontCode2 = module.attributeValue("frontCode2");
			String deviceType = module.attributeValue("type");
			String startCode = module.attributeValue("startCode");
			String endCode = module.attributeValue("endCode");
			JSONObject tmpObj = new JSONObject();
			tmpObj.put("frontCode1", frontCode1);
			tmpObj.put("frontCode2", frontCode2);
			tmpObj.put("startCode", startCode);
			tmpObj.put("endCode", endCode);
			tmpObj.put("deviceType", deviceType);
			deviceTypeArr.add(tmpObj);
		}
	}
	
	public static Properties devConfig = new Properties();
	public static void loadDevConfig(){
		FileInputStream fis;
		try {
			fis = new FileInputStream(getFile("deviceConfig.properties"));
			devConfig.load(fis);
			fis.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	
	}

	public static void loadServerConfig(){
		FileInputStream fis;
		try {
			fis = new FileInputStream(getFile("severParams.properties"));
			devConfig.load(fis);
			tftp_ip = devConfig.getProperty("tftpIP");
			console_server_ip = devConfig.getProperty("consoleServerIP");
			console_server_port[0] = Integer.valueOf(devConfig.getProperty("consolePort1"));
			console_server_port[1] = Integer.valueOf(devConfig.getProperty("consolePort2"));
			console_server_port[2] = Integer.valueOf(devConfig.getProperty("consolePort3"));
			console_server_port[3] = Integer.valueOf(devConfig.getProperty("consolePort4"));
			console_server_port[4] = Integer.valueOf(devConfig.getProperty("consolePort5"));
			console_server_port[5] = Integer.valueOf(devConfig.getProperty("consolePort6"));
			console_server_port[6] = Integer.valueOf(devConfig.getProperty("consolePort7"));
			console_server_port[7] = Integer.valueOf(devConfig.getProperty("consolePort8"));
			fis.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public static int testType = 1;//1 基测 2复测
	public static void loadTestType(){
		FileInputStream fis;
		try {
			Properties type = new Properties();
			fis = new FileInputStream(getFile("testType.properties"));
			type.load(fis);
			testType = Integer.valueOf((String) type.get("testType"));
			fis.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private static void startMysql(){
		CheckMysql checkMySQL = new CheckMysql();
		try {
			checkMySQL.startMySQL();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
